package com.qf.flash.ui.home;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.qf.dblib.dao.impl.UserMgr;
import com.qf.flash.base.BaseRefreshFragment;
import com.qf.flash.model.GameGroupBean;
import com.qf.flash.mvp.contract.GameContract;
import com.qf.flash.mvp.presenter.GameWaitePresenter;
import com.qf.flash.ui.home.adapter.GameGroupItem;
import com.qf.flashlib.adapter.RVAdapter;
import com.qf.flashlib.exception.ApiException;
import com.qf.flashlib.sharedpreferences.SavePermanentSharePrefs;
import com.qf.flashlib.sharedpreferences.SharePrefConstants;
import com.qf.flashlib.widget.ViewUtil;

import java.util.List;

/**
 * 创建日期：2020/2/23 on 20:07
 * 描述:
 * 作者:戴旭东
 */
public class GroupHallFragment extends BaseRefreshFragment implements RVAdapter.OnItemChildClickListener, GameContract.View {
    private RVAdapter<Object> mAdapter;

    private GameWaitePresenter gameWaitePresenter;

    @Override
    protected void initInject() {
        super.initInject();
        gameWaitePresenter = new GameWaitePresenter();
        initPresenters(gameWaitePresenter);
    }

    @Override
    public RecyclerView.LayoutManager getLayoutManager() {
        return new LinearLayoutManager(getActivity());
    }

    @Override
    public RecyclerView.Adapter getRecyclerAdapter() {

        mAdapter = new RVAdapter<>(new GameGroupItem());
        mAdapter.setOnItemChildClickListener(this);
        return mAdapter;
    }

    @Override
    protected void lazyLoad() {
        mRefresh.autoRefresh();
    }


    @Override
    protected void requestData(boolean isRefresh, int page) {
        ViewUtil.setRefreshComplete(mRefresh, isRefresh);
        String areaId = SavePermanentSharePrefs.getInstance().getDataString(SharePrefConstants.AREA_ID);
        gameWaitePresenter.getGameList(UserMgr.getInstance().getLoginUser().getUid(),areaId, page);
    }

    @Override
    public void onItemChildClick( View view, int position) {
        Object data = mAdapter.getData(position);
        if (data instanceof GameGroupBean) {
            GameGroupBean bean = (GameGroupBean) data;
            GroupDetailActivity.start(getActivity(), bean.getId(), bean.getPlayId());
        }

    }

    @Override
    public void setGameList(List<GameGroupBean> data, int totalPage) {
        ViewUtil.setRefreshComplete(mRefresh, isRefresh);
        mRefresh.setEnableLoadMore(page < totalPage);
        List<Object> datas = mAdapter.getDatas();
        if (isRefresh) {
            datas.clear();
        }
        datas.addAll(data);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onError(ApiException e) {
        super.onError(e);
        ViewUtil.setRefreshComplete(mRefresh, isRefresh);
    }
}
